package com.promfy.timetable.ui;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.MeasureSpec;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Scroller;
import android.widget.TextView;

public class MyViewGroup extends ViewGroup {

	private static final String TAG = "p_vg";

	private Scroller scroller;

	private int currentScreenIndex = 1;

	private GestureDetector gestureDetector;

	// 设置一个标志位，防止底层的onTouch事件重复处理UP事件
	public boolean fling;
	
	/*
	 * choose which screen is default screen
	 */
	private int offsetScreen = 1;

	private CourseConfigView ccv;

	private TimetableView tv;

	private ReminderListView rv;

	private int width;
	private int height;
	
	private long courseWidth;
	private long courseHeight;
	private long edgeWidth;

	private int titleHight = 130;
	
	public Scroller getScroller() {
		return scroller;
	}

	public MyViewGroup(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initView(context);
	}

	public MyViewGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		initView(context);
	}

	public MyViewGroup(Context context) {
		super(context);
		initView(context);
	}

	private void initView(final Context context) {

//    	TextView tv1 = new TextView(context);
//		tv1.setBackgroundColor(Color.RED);
//		addView(tv1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//		
//		TextView tv1 = new TextView(context);
//		tv1.setBackgroundColor(Color.YELLOW);
//		addView(tv1, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
//
//		TextView tv11 = new TextView(context);
//		tv11.setBackgroundColor(Color.GREEN);
//		addView(tv11, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));	
		
		//screen one, course config 
		ccv = new CourseConfigView(context);
		addView(ccv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		//screen two, default, timetable
		tv = new TimetableView(context);//,width,height,courseWidth,courseHeight,edgeWidth);
		addView(tv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		//screen three, reminder list
		rv = new ReminderListView(context);
		addView(rv, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		
		this.scroller = new Scroller(context);
		Log.d(TAG, "getScrollX() = " + getScrollX());

		this.gestureDetector = new GestureDetector(new OnGestureListener() {

			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				return false; 
			}

			@Override
			public void onShowPress(MotionEvent e) {
			}

			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2,
					float distanceX, float distanceY) {
				Log.d(TAG, "on scroll>>>>>>>>>>>>>>>>>distanceX<<<<<<<<<<<<<<>>>"+distanceX);
				Log.d(TAG, "on scroll>>>>>>>>>>>>>>>>>distanceX<<<<<<<<<<<<<<>>>"+getScrollX());
				Log.d(TAG, "on scroll>>>>>>>>>>>>>>>>>distanceX<<<<<<<<<<<<<<>>>"+currentScreenIndex);
			//	if ((distanceX > 0 && currentScreenIndex < getChildCount() - 1)// 防止移动过最后一页
			//			|| (distanceX < 0 && getScrollX() > 0)) {// 防止向第一页之前移动
					scrollBy((int) distanceX, 0);
					Log.d(TAG, "on scroll>>>>>>>>>>>>>>>>>防止向第一页之前移动<<<<<<<<<<<<<<>>>");
			//	}
				return true;
			}

			@Override
			public void onLongPress(MotionEvent e) {
			}

			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2,
					float velocityX, float velocityY) {
				Log.d(TAG, "min velocity >>>"
						+ ViewConfiguration.get(context)
								.getScaledMinimumFlingVelocity()
						+ " current velocity>>" + velocityX);
				if (Math.abs(velocityX) > ViewConfiguration.get(context)
						.getScaledMinimumFlingVelocity()) {// 判断是否达到最小轻松速度，取绝对值的
					if (velocityX > 0 && currentScreenIndex > 0) {
						Log.d(TAG, ">>>>fling to left");
						fling = true;
						scrollToScreen(currentScreenIndex - 1);
					} else if (velocityX < 0
							&& currentScreenIndex < getChildCount() - 1) {
						Log.d(TAG, ">>>>fling to right");
						fling = true;
						scrollToScreen(currentScreenIndex + 1);
					}
				}

				return true;
			}

			@Override
			public boolean onDown(MotionEvent e) {
				return false;
			}
		});
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		for (int i = 0; i < getChildCount(); i++) {
			View child = getChildAt(i);
			child.measure(widthMeasureSpec, heightMeasureSpec);
		}
		
		int finalWidth, finalHeight;
		finalWidth = measureWidth(widthMeasureSpec);
		finalHeight = measureHeight(heightMeasureSpec);

		this.width = finalWidth;
		this.height = finalHeight;
		courseWidth = width / 5;
		edgeWidth = courseWidth/2;
		courseHeight = (height - titleHight)  / 6;
		
		rv.setPadding(0, 0, (int)edgeWidth, 0);
		ccv.setPadding((int)edgeWidth, 0, 0, 0);
	}
	
	private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
 
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = specSize;
        }
 
        return result;
    }
     
    private int measureHeight(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
 
        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = specSize;
        }
        return result;
    }
	
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		Log.d(TAG, ">>>>>>>>>>>>>>>>>>>>left: " + left + " top: " + top + " right: " + right
				+ " bottom:" + bottom);

		/**
		 * 设置布局，将子视图顺序横屏排列
		 */
		for (int i = 0; i < getChildCount(); i++) {
			View child = getChildAt(i);
			child.setVisibility(View.VISIBLE);
			//child.measure(right - left, bottom - top);
			int l = 0 + (i-offsetScreen) * getWidth();
			int t = 0;
			int r = getWidth() + (i-offsetScreen) * getWidth();
			int b = getHeight();
			
			child.layout(l, t, r, b);
		}
	}

	@Override
	public void computeScroll() {
		if (scroller.computeScrollOffset()) {
			//Log.d(TAG, ">>>>>>>>>>computeScroll>>>>>"+scroller.getCurrX());

			scrollTo(scroller.getCurrX(), 0);
			postInvalidate();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		gestureDetector.onTouchEvent(event);

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			break;
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
			Log.d(TAG, ">>ACTION_UP:>>>>>>>> MotionEvent.ACTION_UP>>>>>");
			Log.d(TAG, "---getScrollX() = " + getScrollX());
			Log.d(TAG, "---snapToDestination()" + (Math.abs(getScrollX() + (getWidth() / 2))) / getWidth() );
			
			if (!fling) {
				int width = getWidth();
				int scrollX = getScrollX();
				int whichScreen;
				if(scrollX < -width/2){
					whichScreen = 0;
				}else if (scrollX < 0){
					whichScreen = 1;
				}else{
					whichScreen = (scrollX + (width / 2)) / width + offsetScreen;
				}
				snapToDestination(whichScreen);
			}
			fling = false;
			break;
		default:
			break;
		}
		return true;
	}

	/**
	 * 切换到指定屏
	 * 
	 * @param whichScreen
	 */
	public void scrollToScreen(int whichScreen) {
		if (getFocusedChild() != null && whichScreen != currentScreenIndex
				&& getFocusedChild() == getChildAt(currentScreenIndex)) {
			getFocusedChild().clearFocus();
		}

		int delta = (whichScreen-offsetScreen) * getWidth() - getScrollX();
		//add by mfy
		if(whichScreen == 0){
			delta += edgeWidth;
		}else if(whichScreen == 2){
			delta -= edgeWidth;
		}
		Log.d("test", "whichScreen = " + whichScreen);
		Log.d("test", "delta = " + delta);
		scroller.startScroll(getScrollX(), 0, delta, 0, Math.abs(delta) * 2);
		invalidate();

		currentScreenIndex = whichScreen;
	}

	/**
	 * 根据当前x坐标位置确定切换到第几屏
	 */
	private void snapToDestination(int whichScreen) { 
		scrollToScreen(whichScreen);
	}

}
